package com.clound.product.controller;

import com.clound.product.VO.ProductInfoVO;
import com.clound.product.VO.ProductVO;
import com.clound.product.VO.ResultVO;
import com.clound.product.dataObject.ProductCategory;
import com.clound.product.dataObject.ProductInfo;
import com.clound.product.dto.CartDTO;
import com.clound.product.service.CategoryService;
import com.clound.product.service.ProductService;
import com.clound.product.utils.ResultVOUtils;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by zzy on 2018/4/6.
 */
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductService productService;

    @GetMapping("/list")
    public ResultVO<ProductVO> list(){
        List<ProductInfo> productInfoList=productService.findUpAll();
        List<Integer> categoryTypeList=productInfoList.stream().map(ProductInfo::getCategoryType).collect(Collectors.toList());
        List<ProductCategory> productCategoryList=categoryService.findByCategoryTypeIn(categoryTypeList);

        //构建返回结构
        List<ProductVO> productVOList= Lists.newArrayList();
        for(ProductCategory productCategory:productCategoryList){
            ProductVO productVO=new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());
            List<ProductInfoVO> productInfoVOList=Lists.newArrayList();
            for(ProductInfo productInfo:productInfoList){
                if(!productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    continue;
                }
                ProductInfoVO productInfoVO=new ProductInfoVO();
                BeanUtils.copyProperties(productInfo,productInfoVO);
                productInfoVOList.add(productInfoVO);
            }
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        }
        return ResultVOUtils.success(productVOList);
    }

    /**
     * 通过商品ID获取商品列表
     * @param productIdList
     * @return
     */
    @PostMapping("/listForOrder")
    public List<ProductInfo> listForOrder(@RequestBody List<String> productIdList){
        return productService.findByProductIdIn(productIdList);
    }

    @PostMapping("/decreaseStock")
    public void decreaseStock(@RequestBody List<CartDTO> cartDTOList){
        productService.decreaseStock(cartDTOList);
    }
}
